package com.siyue.scheduler;

import com.siyue.handler.MyWebSocketClient;
import com.siyue.handler.SharedData;
import jakarta.annotation.Resource;
import jakarta.websocket.DeploymentException;
import jakarta.websocket.Session;
import jakarta.websocket.WebSocketContainer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 启动websocket服务
 */
@Component
@Slf4j
public class WebSocketPingScheduler {

    @Resource
    WebSocketContainer webSocketContainer;
    @Resource
    MyWebSocketClient webSocketClient;

    @Scheduled(fixedRate = 5000) // 每5秒发送一次ping
    public void sendPing() {
        SharedData.clean();
        if (webSocketClient.getSession() == null || !webSocketClient.getSession().isOpen()) {
            log.info("W1717941148 外呼呼叫 ");
            URI uri = URI.create("ws://127.0.0.1:8080/ws");
            try {
                Session session = webSocketContainer.connectToServer(webSocketClient, uri);
            } catch (DeploymentException | IOException e) {
                // 处理异常
                log.error("W1717941148 外呼异常 {} ", e.getStackTrace());
                SharedData.sessionMap= new ConcurrentHashMap<>();
            }
        }
        log.info("W1717941234 外呼请求ping ");
        webSocketClient.getSession().getAsyncRemote().sendText("ping");
    }

    @Scheduled(cron = "0 0 1 * * ?") // 在凌晨1点执行
    public void qingko() {
        log.error("凌晨初始化");
        SharedData.sessionMap= new ConcurrentHashMap<>();
    }

    @Scheduled(cron = "0 30 12 * * ?")
    public void performTask() {
        log.error("中午初始化");
        System.out.println("执行任务: " + System.currentTimeMillis());
        SharedData.sessionMap= new ConcurrentHashMap<>();
    }
}